<template>
  <div class="math-editor" :class="{ 'inline': inline }">
    <math-field
      :ref="fieldId"
      :value="value"
      @input="handleInput"
      :style="editorStyle"
    ></math-field>
  </div>
</template>

<script>
// 添加导入
import { MathfieldElement } from 'mathlive'

export default {
  name: 'MathEditor',
  props: {
    value: {
      type: String,
      default: ''
    },
    inline: {
      type: Boolean,
      default: false
    },
    fieldId: {
      type: String,
      default: 'mathfield'
    }
  },
  data() {
    return {
      editorStyle: {
        width: this.inline ? 'auto' : '100%',
        minWidth: '200px',
        padding: '8px',
        border: '1px solid var(--borderColor)',
        borderRadius: '4px',
        backgroundColor: 'var(--editorBgColor)'
      }
    }
  },
  
  beforeMount() {
    // 在组件挂载前检查并注册
    if (!customElements.get('math-field')) {
      customElements.define('math-field', MathfieldElement)
    }
  },

  mounted() {
    const mathfield = this.$refs[this.fieldId]
    if (mathfield) {
      mathfield.setOptions({
        smartMode: true,
        smartFence: true,
        keyboardMode: 'auto',
        virtualKeyboards: 'all',
        defaultMode: this.inline ? 'inline-math' : 'math',
        letterShapeStyle: 'tex',
        macros: {
          '\\RR': '\\mathbb{R}',
          '\\NN': '\\mathbb{N}'
        }
      })
    }
  },

  methods: {
    handleInput(evt) {
      const latex = evt.target.value
      this.$emit('input', latex)
      this.$emit('change', {
        latex,
        inline: this.inline
      })
    }
  },
  
  beforeDestroy() {
    this.$store.dispatch('TOGGLE_MATH_EDITOR', {
      show: false,
      type: 'inline',
      content: ''
    })
  }
}
</script>

<style>
.math-editor {
  margin: 10px 0;
  background-color: var(--editorBgColor);
  color: var(--editorColor);
  border-radius: 4px;
  position: relative;
}

.math-editor.inline {
  display: inline-block;
  margin: 0 4px;
}

.math-field {
  font-family: var(--codeFontFamily);
  font-size: var(--codeFontSize);
}
</style>